package com.siyoumi.app.modules.app_fks.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.siyoumi.app.external_api.elasticsearch.EsApi;
import com.siyoumi.app.modules.app_fks.entity.FksMsgEsData;
import com.siyoumi.app.modules.app_fks.vo.FksMsgEsSearchVo;
import com.siyoumi.component.XBean;
import com.siyoumi.component.XSpringContext;
import com.siyoumi.config.SysConfig;
import com.siyoumi.service.IWebService;
import com.siyoumi.util.XReturn;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//es数据，添加，搜索，删除操作
@Slf4j
@Service
public class SvcFksMsgEs
        implements IWebService {
    static public SvcFksMsgEs getBean() {
        return XSpringContext.getBean(SvcFksMsgEs.class);
    }

    private String getIndex() {
        if (SysConfig.getBean().isDev()) {
            return "fks_msg_dev";
        }
        return "fks_msg";
    }

    /**
     * 搜索列表
     */
    public IPage<FksMsgEsData> searchList(FksMsgEsSearchVo vo) {
        IPage<FksMsgEsData> pageData = new Page<>();
        pageData.setCurrent(vo.getPage());
        pageData.setSize(vo.getPageSize());

        Map<String, Object> mapPost = new HashMap<>();
        mapPost.put("from", pageData.offset());
        mapPost.put("size", pageData.getSize());
        mapPost.put("track_total_hits", true);

        List<Object> mapMustItem = new ArrayList<>();
        { //关键词搜索
            Map<String, Object> mapMultiMatchQuery = new HashMap<>();
            mapMultiMatchQuery.put("query", vo.getKeyword());
            mapMultiMatchQuery.put("fields", List.of("fmsg_title", "fmsg_keyword"));
            Map<String, Object> mapMulti = new HashMap<>();
            mapMulti.put("multi_match", mapMultiMatchQuery);

            //Map<String, Object> mapShould = new HashMap<>();
            //mapShould.put("should", mapMulti);
            //Map<String, Object> mapBool = new HashMap<>();
            //mapBool.put("bool", mapShould);
            mapMustItem.add(mapMulti);
        }
        if (vo.getType() != null) { //类型
            Map<String, Object> mapMsgType = new HashMap<>();
            mapMsgType.put("fmsg_type", vo.getType());

            Map<String, Object> mapMatch = new HashMap<>();
            mapMatch.put("match", mapMsgType);
            mapMustItem.add(mapMatch);
        }
        Map<String, Object> mapMust = new HashMap<>();
        mapMust.put("must", mapMustItem);
        Map<String, Object> mapBool = new HashMap<>();
        mapBool.put("bool", mapMust);
        mapPost.put("query", mapBool);

        XReturn r = EsApi.getBean().docSearch(getIndex(), mapPost);
        List<FksMsgEsData> list = new ArrayList<>();
        Integer total = 0;
        if (r.ok()) {
            JSONObject response = r.getData("response");
            JSONObject jsonTotal = response.getJSONObject("total");
            total = jsonTotal.getInteger("value");

            JSONArray hits = response.getJSONArray("hits");
            for (Object item : hits) {
                JSONObject itemJson = (JSONObject) item;
                FksMsgEsData data = jsonToData(itemJson);
                list.add(data);
            }
        }

        pageData.setRecords(list);
        pageData.setTotal(total);
        return pageData;
    }

    public FksMsgEsData getEntity(String id) {
        XReturn r = EsApi.getBean().docInfo(getIndex(), id);
        if (r.err()) {
            return null;
        }

        JSONObject response = r.getData("response");
        FksMsgEsData data = jsonToData(response);

        return data;
    }

    /**
     * api json 转 实体
     * {
     * "_index": "dev",
     * "_type": "_doc",
     * "_id": "122",
     * "_version": 3,
     * "_seq_no": 27,
     * "_primary_term": 2,
     * "found": true,
     * "_source": {
     * "title": "我是满意人,我叫五四",
     * "content": "我是中国人"
     * }
     * }
     *
     * @param response
     */
    protected FksMsgEsData jsonToData(JSONObject response) {
        String dataId = response.getString("_id");
        JSONObject source = response.getJSONObject("_source");

        FksMsgEsData data = XBean.fromMap(source, FksMsgEsData.class);
        data.setId(dataId);
        return data;
    }

    public XReturn edit(FksMsgEsData data) {
        Map<String, Object> mapData = XBean.toMap(data);
        return EsApi.getBean().docUpdate(getIndex(), data.getId(), mapData);
    }

    /**
     * 删除
     */
    @SneakyThrows
    @Transactional(propagation = Propagation.MANDATORY)
    public XReturn delete(List<String> ids) {
        XReturn r = XReturn.getR(0);

        for (String id : ids) {
            EsApi.getBean().docDelete(getIndex(), id);
        }

        return r;
    }


}
